package com.android.core.base;

import android.app.Activity;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * 描述：
 * -
 * 创建人：鲍圣祥
 * 创建时间：2016/12/6
 */
public abstract class BasePresenter<V> {
    private Reference<V> mViewRef;
    private CompositeSubscription mCompositeSubscription;
    protected Activity mActivity;

    public void attachView(V view, Activity activity) {
        mViewRef = new WeakReference<>(view);
        mActivity = activity;
    }

    protected void addSubscribe(Subscription subscription) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscription);
    }

    protected V getView() {
        return mViewRef.get();
    }

    public boolean isViewAttached() {
        return mViewRef != null && mViewRef.get() != null;
    }

    public void detachView() {
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
        unSubscribe();
    }

    public void unSubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.clear();
        }
    }

}
